import { ElMessage } from 'element-plus'

/**
 * 测试辅助工具类
 */
export class TestHelpers {
  /**
   * 验证图片上传功能
   */
  static async validateImageUpload(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      // 检查上传组件是否存在
      const uploadComponent = document.querySelector('.upload-area')
      if (!uploadComponent) {
        return {
          success: false,
          message: '上传组件未找到'
        }
      }

      // 检查拖拽功能
      const dragEvents = ['dragover', 'dragenter', 'dragleave', 'drop']
      const hasDragSupport = dragEvents.every(event => {
        return typeof uploadComponent[`on${event}`] !== 'undefined' || 
               uploadComponent.getAttribute(`on${event}`) !== null
      })

      if (!hasDragSupport) {
        return {
          success: false,
          message: '拖拽上传功能不完整'
        }
      }

      return {
        success: true,
        message: '图片上传功能验证通过'
      }
    } catch (error) {
      return {
        success: false,
        message: `图片上传验证失败: ${error}`
      }
    }
  }

  /**
   * 验证搜索筛选功能
   */
  static async validateSearchFilter(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      // 检查搜索框是否存在
      const searchInput = document.querySelector('.search-input') || 
                         document.querySelector('input[placeholder*="搜索"]')
      if (!searchInput) {
        return {
          success: false,
          message: '搜索框未找到'
        }
      }

      // 检查筛选器是否存在
      const filterComponents = document.querySelectorAll('.filter-item, .tag-filter')
      if (filterComponents.length === 0) {
        return {
          success: false,
          message: '筛选组件未找到'
        }
      }

      return {
        success: true,
        message: '搜索筛选功能验证通过'
      }
    } catch (error) {
      return {
        success: false,
        message: `搜索筛选验证失败: ${error}`
      }
    }
  }

  /**
   * 验证文案生成功能
   */
  static async validateTextGeneration(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      // 检查文案生成面板是否存在
      const textPanel = document.querySelector('.text-generation-panel') ||
                       document.querySelector('.generate-panel')
      if (!textPanel) {
        return {
          success: false,
          message: '文案生成面板未找到'
        }
      }

      // 检查风格选择器
      const styleSelector = document.querySelector('.style-selector') ||
                           document.querySelector('select[name*="style"]')
      if (!styleSelector) {
        return {
          success: false,
          message: '风格选择器未找到'
        }
      }

      // 检查生成按钮
      const generateButton = document.querySelector('.generate-btn') ||
                            document.querySelector('button[class*="generate"]')
      if (!generateButton) {
        return {
          success: false,
          message: '生成按钮未找到'
        }
      }

      return {
        success: true,
        message: '文案生成功能验证通过'
      }
    } catch (error) {
      return {
        success: false,
        message: `文案生成验证失败: ${error}`
      }
    }
  }

  /**
   * 验证图片扩展功能
   */
  static async validateImageExpansion(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      // 检查图片展示区域
      const imageGrid = document.querySelector('.image-grid') ||
                       document.querySelector('.expand-results')
      if (!imageGrid) {
        return {
          success: false,
          message: '图片展示区域未找到'
        }
      }

      // 检查扩展按钮
      const expandButton = document.querySelector('.expand-btn') ||
                          document.querySelector('button[class*="expand"]')
      if (!expandButton) {
        return {
          success: false,
          message: '扩展按钮未找到'
        }
      }

      return {
        success: true,
        message: '图片扩展功能验证通过'
      }
    } catch (error) {
      return {
        success: false,
        message: `图片扩展验证失败: ${error}`
      }
    }
  }

  /**
   * 验证图文组合功能
   */
  static async validateImageTextCompose(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      // 检查模板选择器
      const templateSelector = document.querySelector('.template-selector') ||
                              document.querySelector('.template-grid')
      if (!templateSelector) {
        return {
          success: false,
          message: '模板选择器未找到'
        }
      }

      // 检查预览区域
      const previewArea = document.querySelector('.preview-area') ||
                         document.querySelector('.compose-preview')
      if (!previewArea) {
        return {
          success: false,
          message: '预览区域未找到'
        }
      }

      // 检查导出按钮
      const exportButton = document.querySelector('.export-btn') ||
                          document.querySelector('button[class*="export"]')
      if (!exportButton) {
        return {
          success: false,
          message: '导出按钮未找到'
        }
      }

      return {
        success: true,
        message: '图文组合功能验证通过'
      }
    } catch (error) {
      return {
        success: false,
        message: `图文组合验证失败: ${error}`
      }
    }
  }

  /**
   * 验证响应式设计
   */
  static async validateResponsiveDesign(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      const originalWidth = window.innerWidth
      const testViewports = [
        { width: 1920, name: '桌面' },
        { width: 768, name: '平板' },
        { width: 375, name: '手机' }
      ]

      let issues: string[] = []

      for (const viewport of testViewports) {
        // 模拟视口变化
        Object.defineProperty(window, 'innerWidth', {
          writable: true,
          configurable: true,
          value: viewport.width
        })

        // 触发resize事件
        window.dispatchEvent(new Event('resize'))

        // 等待DOM更新
        await new Promise(resolve => setTimeout(resolve, 100))

        // 检查关键元素是否可见
        const mainContent = document.querySelector('.main-content') ||
                           document.querySelector('main')
        if (mainContent) {
          const rect = mainContent.getBoundingClientRect()
          if (rect.width > viewport.width) {
            issues.push(`${viewport.name}视口下内容溢出`)
          }
        }

        // 检查导航菜单
        const navigation = document.querySelector('.navigation') ||
                          document.querySelector('nav')
        if (navigation && viewport.width < 768) {
          const isHidden = window.getComputedStyle(navigation).display === 'none'
          const isMobile = navigation.classList.contains('mobile-nav')
          if (!isHidden && !isMobile) {
            issues.push(`${viewport.name}视口下导航未适配`)
          }
        }
      }

      // 恢复原始视口宽度
      Object.defineProperty(window, 'innerWidth', {
        writable: true,
        configurable: true,
        value: originalWidth
      })
      window.dispatchEvent(new Event('resize'))

      if (issues.length > 0) {
        return {
          success: false,
          message: `响应式设计问题: ${issues.join(', ')}`
        }
      }

      return {
        success: true,
        message: '响应式设计验证通过'
      }
    } catch (error) {
      return {
        success: false,
        message: `响应式设计验证失败: ${error}`
      }
    }
  }

  /**
   * 验证错误处理机制
   */
  static async validateErrorHandling(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      let errorHandled = false

      // 监听全局错误
      const originalErrorHandler = window.onerror
      window.onerror = (message, source, lineno, colno, error) => {
        errorHandled = true
        if (originalErrorHandler) {
          return originalErrorHandler(message, source, lineno, colno, error)
        }
        return false
      }

      // 模拟一个错误
      try {
        throw new Error('测试错误')
      } catch (error) {
        // 错误被捕获，这是好的
      }

      // 检查是否有错误边界组件
      const errorBoundaries = document.querySelectorAll('[data-error-boundary]')
      
      // 检查是否有加载状态指示器
      const loadingIndicators = document.querySelectorAll('.loading, .el-loading-mask')
      
      // 恢复原始错误处理器
      window.onerror = originalErrorHandler

      return {
        success: true,
        message: `错误处理验证通过 (错误边界: ${errorBoundaries.length}, 加载指示器: ${loadingIndicators.length})`
      }
    } catch (error) {
      return {
        success: false,
        message: `错误处理验证失败: ${error}`
      }
    }
  }

  /**
   * 验证用户体验
   */
  static async validateUserExperience(): Promise<{
    success: boolean
    message: string
  }> {
    try {
      const issues: string[] = []

      // 检查页面加载时间
      const loadTime = performance.now()
      if (loadTime > 3000) {
        issues.push('页面加载时间过长')
      }

      // 检查可访问性
      const focusableElements = document.querySelectorAll(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      )
      if (focusableElements.length === 0) {
        issues.push('缺少可聚焦元素')
      }

      // 检查图片alt属性
      const images = document.querySelectorAll('img')
      const imagesWithoutAlt = Array.from(images).filter(img => !img.alt)
      if (imagesWithoutAlt.length > 0) {
        issues.push(`${imagesWithoutAlt.length}张图片缺少alt属性`)
      }

      // 检查颜色对比度（简单检查）
      const textElements = document.querySelectorAll('p, span, div, h1, h2, h3, h4, h5, h6')
      let lowContrastCount = 0
      
      Array.from(textElements).slice(0, 10).forEach(element => {
        const styles = window.getComputedStyle(element)
        const color = styles.color
        const backgroundColor = styles.backgroundColor
        
        // 简单的对比度检查（实际应该使用更复杂的算法）
        if (color === backgroundColor || 
            (color.includes('rgb(128') && backgroundColor.includes('rgb(128'))) {
          lowContrastCount++
        }
      })

      if (lowContrastCount > 0) {
        issues.push(`${lowContrastCount}个元素可能存在对比度问题`)
      }

      if (issues.length > 0) {
        return {
          success: false,
          message: `用户体验问题: ${issues.join(', ')}`
        }
      }

      return {
        success: true,
        message: '用户体验验证通过'
      }
    } catch (error) {
      return {
        success: false,
        message: `用户体验验证失败: ${error}`
      }
    }
  }

  /**
   * 创建测试用的模拟数据
   */
  static createMockData() {
    return {
      images: [
        {
          id: 1,
          filename: 'test-image-1.jpg',
          url: '/uploads/test-image-1.jpg',
          tags: ['风景', '自然', '山水'],
          uploadTime: new Date().toISOString(),
          size: 1024000
        },
        {
          id: 2,
          filename: 'test-image-2.jpg',
          url: '/uploads/test-image-2.jpg',
          tags: ['建筑', '城市', '现代'],
          uploadTime: new Date().toISOString(),
          size: 2048000
        }
      ],
      texts: [
        {
          id: 1,
          content: '山水如画，美不胜收',
          type: 'short',
          style: 'creative',
          imageId: 1
        },
        {
          id: 2,
          content: '这是一幅令人叹为观止的山水画卷，展现了大自然的鬼斧神工...',
          type: 'long',
          style: 'professional',
          imageId: 1
        }
      ]
    }
  }

  /**
   * 模拟API响应
   */
  static mockApiResponse(data: any, delay: number = 1000): Promise<any> {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          success: true,
          data,
          timestamp: Date.now()
        })
      }, delay)
    })
  }

  /**
   * 模拟API错误
   */
  static mockApiError(message: string, code: number = 500, delay: number = 1000): Promise<never> {
    return new Promise((_, reject) => {
      setTimeout(() => {
        reject({
          success: false,
          error: {
            code,
            message
          },
          timestamp: Date.now()
        })
      }, delay)
    })
  }

  /**
   * 检查浏览器兼容性
   */
  static checkBrowserCompatibility(): {
    compatible: boolean
    issues: string[]
  } {
    const issues: string[] = []

    // 检查必要的API支持
    if (!window.fetch) {
      issues.push('不支持Fetch API')
    }

    if (!window.FormData) {
      issues.push('不支持FormData')
    }

    if (!window.FileReader) {
      issues.push('不支持FileReader')
    }

    if (!window.localStorage) {
      issues.push('不支持localStorage')
    }

    if (!document.querySelector) {
      issues.push('不支持querySelector')
    }

    // 检查ES6特性
    try {
      eval('const test = () => {}')
    } catch (error) {
      issues.push('不支持ES6箭头函数')
    }

    try {
      eval('const [a, b] = [1, 2]')
    } catch (error) {
      issues.push('不支持ES6解构赋值')
    }

    return {
      compatible: issues.length === 0,
      issues
    }
  }
}

// 导出测试辅助工具实例
export const testHelpers = new TestHelpers()